/*
 * Copyright (C) 2011 Olivier Pothin and contributors
 *
 * GNU General Public License v2.0
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */
/**
 * 
 * @author Olivier Pothin
 *
 */
package opot.webservices.impl;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import opot.dto.Word;
import opot.webservices.IDatabaseService;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.util.Xml;


public class DatabaseServiceImpl implements IDatabaseService {

	private XmlPullParser parser;

	public DatabaseServiceImpl() {
		parser = Xml.newPullParser();
	}

	@Override
	public List<Word> getIntialisationQuery(int databaseVerson,URL url) {
		List<Word> arrayWords = new ArrayList<Word>();
		
		try {
			parser.setInput(new InputStreamReader(url.openStream()));

			int eventType = parser.getEventType();
			String tag = null;
			Word currentWord = null;
			
			
			
			while (eventType != XmlPullParser.END_DOCUMENT){
				switch (eventType){
				case XmlPullParser.START_DOCUMENT:

					break;
				case XmlPullParser.END_TAG:
					tag = parser.getName();
					
					if(tag.equalsIgnoreCase("word")){
						if (currentWord != null) {
							arrayWords.add(currentWord);
						}
					}			
					
					break;

				case XmlPullParser.START_TAG:
					tag = parser.getName();

					if(tag.equalsIgnoreCase("word")){
						currentWord = new Word();
					}

					if(tag.equalsIgnoreCase("zh")){
						currentWord.zh = parser.nextText();
					}
					
					if(tag.equalsIgnoreCase("pin")){
						currentWord.pin = parser.nextText();
					}
					
					if(tag.equalsIgnoreCase("fr")){
						currentWord.fr = parser.nextText();
					}
					
					break;
				}
				eventType = parser.next();
			}
			

		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return arrayWords;
	}
}
